package com.ww.juc.threadpool;

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.concurrent.*;

/**
 * TODO
 *
 * @author wanggw
 * @date 2024-01-07 16:08:23
 */
public class ThreadPoolDemo {

    private final static int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();

    private final static ThreadPoolExecutor POOL_EXECUTOR = new ThreadPoolExecutor(AVAILABLE_PROCESSORS,
            AVAILABLE_PROCESSORS * 2,
            1,
            TimeUnit.MINUTES,
            new LinkedBlockingQueue<>(5),
            new NamedThreadFactory("异步线程池", false),
            new ThreadPoolExecutor.CallerRunsPolicy());

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        long start = System.currentTimeMillis();

        // 异步执行任务A
//        POOL_EXECUTOR.execute(() -> {
//            try {
//                doSomethingA();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
        Future<String> resultA1 = POOL_EXECUTOR.submit(ThreadPoolDemo::doSomethingA1);
        // 同步等待任务A1执行结果
        System.out.println(resultA1.get());

//        // 同步执行线程B
//        doSomethingB();
        POOL_EXECUTOR.execute(() -> {
            try {
                doSomethingB();
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        System.out.println("耗时：" + (System.currentTimeMillis() - start) + "毫秒");

        // 挂起当前线程
        Thread.currentThread().join();
    }

    private static void doSomethingA() {
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("小睡2秒钟...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static String doSomethingA1() {
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("小睡2秒钟...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "A1任务执行完成";
    }

    private static void doSomethingB() {
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println("小睡1秒钟...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static String doSomethingB1() {
        try {
            TimeUnit.SECONDS.sleep(1);
            System.out.println("小睡1秒钟...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return "B1任务执行完成";
    }
}
